<template>
  <div class="record-detail">
    <HeaderNav :bgStyle="bgStyle" />

    <div class="custom-main">
      <van-form @submit="onSubmit">
        <div class="main-header">
          <div class="custom-info">
            <img
              v-if="customerDetail.logo"
              :src="getLogo(customerDetail.logo)"
              alt=""
            />
            <div class="name">
              {{ customerDetail.zhName }}
            </div>
          </div>

          <div class="visit-form">
            <van-cell-group inset>
              <!--              <van-field-->
              <!--                v-model="recordForm.visitDate"-->
              <!--                required-->
              <!--                name="拜访时间"-->
              <!--                label="拜访时间"-->
              <!--                placeholder="拜访时间"-->
              <!--                :rules="[{ required: true, message: '请选择拜访时间' }]"-->
              <!--              />-->

              <van-field
                v-model="recordForm.visitDate"
                is-link
                readonly
                name="拜访时间"
                label="拜访时间"
                placeholder="点击选择时间"
                @click="showPicker = true"
                :rules="[{ required: true, message: '请选择拜访时间' }]"
              />
              <DateTime
                :values="recordForm.visitDate"
                @changeValue="showPicker = false"
                :showPicker="showPicker"
                @confirm="onConfirm"
              />

              <van-field
                v-model="recordForm.visitor"
                name="客户经理"
                label="客户经理"
                placeholder="客户经理"
                readonly
              />
              <van-field
                v-model="recordForm.visitees"
                required
                name="拜访对象"
                label="拜访对象"
                placeholder="请输入拜访对象"
                :rules="[{ required: true, message: '请输入拜访对象' }]"
              />
              <van-field
                v-model="peersNames"
                name="同行人"
                label="同行人"
                placeholder="请选择同行人"
                @focus="addPeople"
                type="textarea"
                autosize
                readonly
              />
            </van-cell-group>
          </div>
        </div>

        <div class="main-content">
          <van-cell-group inset>
            <van-field
              v-model="recordForm.visitTitle"
              required
              name="标题"
              label="标题"
              placeholder="标题编辑"
              :rules="[{ required: true, message: '请输入标题' }]"
            />
            <van-field
              v-model="recordForm.details"
              name="内容"
              label="内容"
              placeholder="内容编辑"
              rows="6"
              autosize
              type="textarea"
              maxlength="500"
              show-word-limit
              :rules="[{ required: true, message: '请输入内容' }]"
            />
          </van-cell-group>
          <van-cell-group inset>
            <ImageUpload v-model="recordForm.imageUrl" />
          </van-cell-group>
          <van-cell-group inset class="!mt-[1rem] pb-[1rem]">
            <FileUpload
              :max="20"
              :file-list="annexList"
              @success="uploadFile"
            />
          </van-cell-group>
        </div>

        <div class="mt-[1rem]">
          <van-button
            :loading="btnLoading"
            block
            type="primary"
            native-type="submit"
            color="linear-gradient(to right, #ffadb3, #ff4350)"
          >
            发布
          </van-button>
        </div>
      </van-form>
    </div>

    <van-popup v-model:show="showPeople" round position="bottom">
      <van-field
        v-model="keyWords"
        clearable
        label="用户名"
        placeholder="请输入用户名搜索"
      />

      <div class="people-box">
        <van-checkbox-group
          v-model="recordForm.peersName"
          shape="square"
          class="people-checkbox"
        >
          <van-checkbox
            v-for="(item, index) of searchPeers"
            :key="index"
            :name="item.userId"
            >{{ item.nickName }}</van-checkbox
          >
        </van-checkbox-group>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts" name="RecordDetail">
import { computed, ref, watch } from "vue";
import { getLogo } from "@/utils";
import { useRoute, useRouter } from "vue-router";
import useUserStore from "@/store/modules/user";
import { recordDetail, saveRecord, updateRecord } from "./fetchData";
import { customDetail } from "@/views/home/custom/fetchData";
import { closeToast, showLoadingToast, showSuccessToast } from "vant";
import HeaderNav from "@/components/headerNav/index.vue";
import ImageUpload from "@/components/imageUpload/index.vue";
import FileUpload from "@/components/fileUpload/index.vue";
import { getUserList } from "@/views/sharedCalendar/fetchData";
import DateTime from "@/components/DateTime/index.vue";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const customId = computed(() => route.query.customId as string);
const id = computed(() => route.query.recordId as string);
const customerDetail = ref<Record<string, any>>({});
const initForm = () => {
  return {
    id: "",
    addPeersIds: "",
    delPeersIds: "",
    customId: customId.value,
    visitTitle: "",
    visitDate: "",
    details: "",
    annexUrl: "",
    visitor: userStore.nickname,
    visitees: "",
    peersName: [] as string[],
    imageUrl: "",
    customName: "",
    peersNameList: []
  };
};
const recordForm = ref(initForm());
const annexList = ref<string[]>([]);
const btnLoading = ref(false);
const bgStyle = computed(() => {
  return {
    background: `url(${getLogo(customerDetail.value.logo)}) no-repeat center`
  };
});
const showPeople = ref(false);
const peersNameList = ref<string[]>([]);
const peersList = ref<Record<string, any>[]>([]);
const peersNames = computed(() => {
  const arr = [];
  peersList.value.forEach(item => {
    if (
      recordForm.value.peersName &&
      recordForm.value.peersName.includes(item.userId)
    )
      arr.push(item.nickName);
  });
  return arr.join(",");
});
const showPicker = ref(false);
const keyWords = ref("");
const searchPeers = computed(() => {
  if (!keyWords.value) return peersList.value;
  return peersList.value.filter(item => item.nickName.includes(keyWords.value));
});

function onConfirm(selectedValues: string) {
  recordForm.value.visitDate = selectedValues;
  showPicker.value = false;
}

function backToHome() {
  router.back();
}

function addPeople() {
  showPeople.value = true;
}

function uploadFile(arr: string[]) {
  recordForm.value.annexUrl = arr.join(",");
}

function onSubmit() {
  recordForm.value.addPeersIds = recordForm.value.peersName.join(",");
  btnLoading.value = true;
  if (recordForm.value.id) {
    const delIds: string[] = [];
    peersNameList.value.forEach(item => {
      if (!recordForm.value.peersName.includes(item)) delIds.push(item);
    });
    recordForm.value.delPeersIds = delIds.join(",");
    updateRecord(recordForm.value)
      .then((res: any) => {
        if (+res.code === 200) {
          showSuccessToast("修改成功");
          userStore.customInfo = {};
          backToHome();
        }
      })
      .finally(() => (btnLoading.value = false));
  } else {
    saveRecord(recordForm.value)
      .then((res: any) => {
        if (+res.code === 200) {
          showSuccessToast("新增成功");
          userStore.customInfo = {};
          backToHome();
        }
      })
      .finally(() => (btnLoading.value = false));
  }
}

function getCustomDetail() {
  customDetail(customId.value).then(res => {
    customerDetail.value = res.data;
  });
}

function getDetail() {
  showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    overlay: true,
    message: "加载中..."
  });
  recordDetail(id.value)
    .then((res: any) => {
      recordForm.value = res.data;
      annexList.value = res.data.annexUrl ? res.data.annexUrl.split(",") : [];
      recordForm.value.visitor = res.data.visitor;

      recordForm.value.peersName = [];
      const arr = recordForm.value.peersNameList || [];
      arr.forEach((item: Record<string, string>) => {
        recordForm.value.peersName.push(...Object.keys(item));
      });
      peersNameList.value = JSON.parse(
        JSON.stringify(recordForm.value.peersName)
      );
    })
    .finally(() => closeToast());
}

function getUsers() {
  getUserList().then((res: any) => {
    peersList.value = res || [];
  });
}

getUsers();

watch(
  () => route.query,
  () => {
    recordForm.value = initForm();
    customerDetail.value = userStore.customInfo;
    if (JSON.stringify(customerDetail.value) === "{}" && customId.value)
      getCustomDetail();
    if (id.value) getDetail();
  },
  { immediate: true }
);
</script>

<style scoped lang="less">
.record-detail {
  background-color: #f3f4fa;

  .custom-bg {
    width: 100%;
    height: 12rem;
    background-color: #ff3040;
    background-size: contain;

    .operate-btn {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 1rem;

      .back {
        width: 2rem;
        height: 2rem;
      }
    }
  }

  .custom-main {
    position: absolute;
    top: 4rem;
    left: 0;
    width: 100%;
    height: calc(100% - 7.5rem);
    display: flex;
    flex-direction: column;
    padding: 1rem;
    overflow: auto;

    .main-header {
      padding: 1rem;
      background-color: #fff;
      border-radius: 0.5rem;

      .custom-info {
        display: flex;
        align-items: center;

        img {
          width: 2.6rem;
          height: 2.6rem;
          border-radius: 1.3rem;
          object-fit: contain;
        }

        .name {
          width: calc(100% - 3rem);
          margin-left: 0.6rem;
          font-size: 1.2rem;
          font-weight: 700;
        }
      }

      .visit-form {
        margin-top: 0.8rem;
      }
    }

    .main-content {
      margin-top: 0.6rem;
      border-radius: 0.5rem;
      background-color: #fff;
    }
  }

  .people-checkbox {
    padding: 1rem 1rem 0.5rem 2.2rem;

    .van-checkbox {
      margin-bottom: 1rem;
    }
  }

  .people-box {
    height: 46vh;
    overflow: auto;
  }
}
</style>
